import importlib
import inspect
import os
import pkgutil
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from config import DB_URL, lib_path

engine = create_engine(DB_URL)


class Environment:

    def initialize(self):
        self._init_db_()
        self._import_all_modules_()

    def _init_db_(self):
        self.db = sessionmaker(engine)()
        self.engine = engine

    def _import_all_modules_(self):
        """
        加载目录下所有的模型
        """
        # 获取目录的配置(目录必须是一个包，才会有__path__属性)
        _modules = []
        for _path in lib_path:
            _modules += self.get_all_modules(_path, "model")

        # 加载所有的类
        for _module in _modules:
            inspect.getmembers(_module, inspect.isclass)

    def get_all_modules(self, path, file_name):
        """
        获取路径下的所有file_name的module
        """
        _app = importlib.import_module(path)

        def get_all_moudules_name(package_path, prefix=""):
            # 用于深度遍历文件夹
            for loader, name, is_package in pkgutil.iter_modules([package_path]):
                if is_package:
                    # 如果还是一个包，那么再次遍历，且遍历的时候加上前缀
                    for _name in get_all_moudules_name(os.path.join(package_path, name), prefix=f"{name}."):
                        yield prefix + _name
                else:
                    yield prefix + name

        return [
            importlib.import_module(f"{path}.{module_name}")
            for module_name in get_all_moudules_name(_app.__path__[0])
            if module_name.split(".")[-1][:len(file_name)] == file_name
        ]


environment = Environment()
